package com.ruoyi.web.controller.api.webapp;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.house.domain.ZuInfo;
import com.ruoyi.house.service.IZuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 房源出租信息（大部分数据来自安居客）Controller
 *
 * @author ruoyi
 * @date 2024-06-20
 */
@RestController
@RequestMapping("/api/webapp/house/info")
public class WAppZuInfoController extends BaseController {
    @Autowired
    private IZuInfoService zuInfoService;

    /**
     * 查询房源出租信息（大部分数据来自安居客）列表
     */
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(ZuInfo zuInfo) {
        startPage();
        List<ZuInfo> list = zuInfoService.selectZuInfoList(zuInfo);
        return getDataTable(list);
    }


    /**
     * 获取房源出租信息（大部分数据来自安居客）详细信息
     */
    @Anonymous
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(zuInfoService.selectZuInfoById(id));
    }


    /**
     * 新增房源出租信息（大部分数据来自安居客）
     */
    @PostMapping
    public AjaxResult add(@RequestBody ZuInfo zuInfo) {


        setAccurateAddress(zuInfo);
        zuInfo.setHouseStatus("待租");
        zuInfo.setUserId(getLoginUser().getUserId());
        int rows = zuInfoService.insertZuInfo(zuInfo);
        if (rows > 0) {

            //插入成功，更新房源编号
            ZuInfo up = new ZuInfo();
            up.setHouseNumber(zuInfo.getId().toString());
            up.setId(zuInfo.getId());
            zuInfoService.updateById(up);
        }

        return toAjax(rows);
    }

    /**
     * 设置精准的地址：city、district、street、plot
     * @param zuInfo
     */
    private void setAccurateAddress(ZuInfo zuInfo) {
        String fullAddress = zuInfo.getFullAddress();
        if(StringUtils.isNull(fullAddress)){
            throw new ServiceException("小区位置不能为空");
        }

        String[] accurateAddressArr = fullAddress.split("-");
        if(accurateAddressArr.length != 4){
            throw new ServiceException("小区位置格式不正确，请以市-区-街道-小区格式输入");
        }

        zuInfo.setCity(accurateAddressArr[0]);
        zuInfo.setDistrict(accurateAddressArr[1]);
        zuInfo.setStreet(accurateAddressArr[2]);
        zuInfo.setPlot(accurateAddressArr[3]);
    }

}